<style lang="less">
    .quill-editor {
        height: 580px;
        .ql-container {
            height: 480px;
        }
    }
    .preview .ivu-modal-mask, .preview .ivu-modal-wrap { 
        z-index: 10000;
    }
</style>

<template>
    <div>
        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80" >
            <Row>
                <Col span="14">
                    <FormItem label="课程内容" prop="content">
                        <quill-editor v-model="formValidate.content"
                            ref="myQuillEditor"
                            :options="editorOption"
                        >
                        </quill-editor>
                        <Upload ref="conUpload" 
                        :show-upload-list="false"
                        :format="['jpg', 'jpeg', 'png']" 
                        :on-format-error="handleFormatError"
                        :on-success="conImgUploadSuccess" 
                        :headers="headers" 
                        :action="contentImgAction">
                            <Button id="contentImg" v-show="false"></Button>
                        </Upload>
                    </FormItem>
                </Col>
                <Col span="10">
                    <FormItem label="课程名称" prop="name">
                        <Input v-model="formValidate.name" placeholder="请输入课程名称"></Input>
                    </FormItem>
                    <FormItem label="课程分类" prop="class_id" >
                        <Select v-model="formValidate.class_id" placeholder="请选择课程分类">
                            <Option v-for="item in classList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="可得学分" prop="points">
                        <Input v-model.number="formValidate.points" placeholder="请输入学习课程可得学分"></Input>
                    </FormItem>
                    <FormItem label="课程简介" prop="describe">
                        <Input v-model="formValidate.describe" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入课程介绍"></Input>
                    </FormItem>
                    <FormItem label="排序值" prop="listorder">
                        <Input v-model.number="formValidate.listorder" placeholder="请输入课程排序值"></Input>
                    </FormItem>
                    <FormItem label="课程首图" prop="headimg">
                        <div>
                                <Upload 
                                ref="upload"
                                :max-size="2048"
                                :format="['jpg','jpeg','png']"
                                :on-format-error="handleFormatError"
                                :on-exceeded-size="handleMaxSize"
                                :on-success="handleUploadSuccess"
                                :on-remove="handleRemoveFile"
                                :default-file-list="defaultList"
                                :on-preview="handlePreview" 
                                :before-upload="handleBeforeUpload"   
                                type="drag"
                                :headers= "headers"
                                :action="headimgAction" >
                                    <div style="padding: 20px 0">
                                        <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                                        <p>点击或将文件拖拽到这里上传</p>
                                    </div>
                                </Upload>
                                <Input v-model="formValidate.headimg" v-show="false"</Input>
                            </div>
                    </FormItem>
                    <FormItem>
                        <Button type="primary" @click="handleSubmit('formValidate')" :disabled="isDisabled">提交</Button>
                        <Button type="ghost" @click="handleReset('formValidate')" style="margin-left: 8px">重置</Button>
                    </FormItem>
                </Col>
            </Row>
        </Form>
        <Modal title="预览图片" v-model="visible" class="preview">
            <img :src="pre_img_url" style="width: 100%">
            <div slot="footer"></div>
        </Modal>
    </div>
</template>

<script>
import http from '../../../libs/http';
import { quillEditor } from 'vue-quill-editor'
import Cookies from 'js-cookie';
export default {
    components: {
        quillEditor
    },
    data () {
        return {
            editorOption: {  // some quill options
                placeholder: '请输入课程文章内容'
            },
            isDisabled: false,  //是否禁用提交按钮
            classList: [], //课程分类列表
            headimgAction: this.host + 'admin/course/uploadHeadImg',  //首图上传方法
            contentImgAction: this.host + 'admin/course/uploadContentImg',  //文章内容图片上传
            uploadList: [], //上传首图列表
            defaultList: [{name:'',url:''}],   //已上传首图列表
            visible: false, //预览窗口
            pre_img_url: '', //预览图片路径
            formValidate: {
                name: '',
                describe: '',
                class_id: '',
                points:'',
                listorder:'',
                headimg: '',
                content:'',
            },
            ruleValidate: {
                name: [
                    { required: true, message: '课程名不能为空', trigger: 'blur' }
                ],
                class_id: [
                    { type: 'number', required: true, message: '请选择课程分类', trigger: 'change' }
                ],
                describe: [
                    { required: true, message: '请输入课程简介', trigger: 'blur' },
                    { type: 'string', min: 1, message: '课程简介不能为空', trigger: 'blur' }
                ],
                points: [
                    { type:'number', required: true, message: '学习课程可得学分为空或格式错误', trigger: 'blur'},
                ],
                listorder: [
                    {type: 'number', message: '请输入数字', trigger: 'blur'}
                ],
                headimg: [
                    { required: true, message: '课程首图不能为空', trigger: 'blur'}
                ],
                content: [
                    { required: true, message: '课程内容不能为空', trigger: 'blur'}
                ]
            }
        }
    },
    methods: {
        handleSubmit (name) {  //提交按钮处理事件
            this.$refs[name].validate((valid) => {
                if (valid) {
                    //提交后台
                    var data = {
                        id: this.formValidate.id,
                        name: this.formValidate.name,
                        describe: this.formValidate.describe,
                        class_id: this.formValidate.class_id,
                        class_type: 2,  //课程类型为文章
                        points: this.formValidate.points,
                        listorder: this.formValidate.listorder,
                        headimg: this.formValidate.headimg,
                        content: this.formValidate.content
                    }
                    this.apiPost('admin/course/update', data).then((res) => {
                        if (res.code != 200) {
                            this.handleError(res);
                        } else {
                            this.$Message.success('编辑课程成功');
                            this.handleReset(name);  //清空表单内容
                            this.$refs.upload.clearFiles();  //清空显示的上传列表
                            this.uploadList = []; //清空上传列表
                            this.$emit('closeEdit');
                        }
                    })
                } else {
                    this.$Message.error('表单验证失败!');
                }
            })
        },
        handleReset (name) {  //重置按钮
            this.$refs[name].resetFields();
        },
        getClassCate() {    //获取课程分类
            var that = this
            var url = 'admin/classCate/index/type/2';
            this.apiGet(url).then((res) => {
                if (res.code != 200) {
                    this.handleError(res);
                } else {
                    that.classList = res.data.list;
                }
            })
        },
        getCourseInfo(id) {  //获取课程信息
            var that = this;
            var url = 'admin/course/read/' + id;
            this.apiGet(url).then((res) => {
                if (res.code != 200) {
                    this.handleError(res);
                } else {
                    that.formValidate = {
                        id: res.data.id,
                        name: res.data.name,
                        describe: res.data.describe,
                        class_id: res.data.class_id,
                        points: res.data.points,
                        listorder: res.data.listorder,
                        headimg: res.data.headimg,
                        content: res.data.content
                    }
                    //获取已上传的图片及文件名
                    var str = res.data.headimg;
                    that.defaultList[0].url = str;
                    that.defaultList[0].name = str.substring(str.length-32, str.length);
                   
                    this.getClassCate();  //获取课程分类列表
                }
            })
        },
        handleBeforeUpload () {  //上传前处理
            const check = this.uploadList.length < 1;
            if (!check) {
                this.$Notice.warning({
                    title: '每次仅能上传一张图片'
                });
            } else {
                this.isDisabled = true;
            }
            return check;
        },
        handleFormatError (file) {  //图片上传格式
            this.isDisabled = false;
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
            });
        },       
        handleMaxSize (file) {  //图片过大
            this.isDisabled = false;
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
            });
        },       
        handleUploadSuccess (res, file) {  //图片上传成功
            if (res.code != 200) {
                this.handleError(res)
            } else {
                this.isDisabled = false;
                this.formValidate.headimg = res.data;
                file.url = res.data;
            }
        },        
        handleRemoveFile (file) {  //删除已上传图片
            this.$Modal.confirm({
                width: "200",
                content: '确认是否删除',
                onOk: () => {
                    var data = { url: file.url }
                    this.apiPost('admin/course/deleteFile', data).then((res) => {
                        if (res.code != 200) {
                            this.handleError(res);
                        } else {
                            this.formValidate.headimg = '';
                        }
                    });
                }
            });
        },
        handlePreview (file) {  //预览窗口
            this.pre_img_url = file.url;
            this.visible = true;
        },
        conImgUploadSuccess (res, file) {  //文章内容图片上传成功
            if (res.code != 200) {
                this.handleError(res) 
            } else {
                this.$refs.myQuillEditor.quill.insertEmbed(this.$refs.myQuillEditor.quill.getSelection().index, 'image', res.data);
            }
        }
    },
    //计算属性,返回header头
    computed: {
        headers() {
            return {
                'authKey': Cookies.get('authKey'),
                'sessionId': Cookies.get('sessionId')
            }
        },
        editor() {
            return this.$refs.myQuillEditor.quill
        }
    },
    mounted() {
    // you can use current editor object to do something(quill methods)
        var vm = this
        var imgHandler = async function(state) {
            vm.addImgRange = vm.$refs.myQuillEditor.quill.getSelection()
            if (state) { //上传图片按钮被点击
                let fileInput = document.getElementById('contentImg')
                fileInput.click() // 加一个触发事件
            //button is clicked
            }
        }
        vm.$refs.myQuillEditor.quill.getModule("toolbar").addHandler("image", imgHandler)
        this.uploadList = this.$refs.upload.fileList; //上传列表
    },
    mixins: [http],
}
</script>

